using System;
using System.Security.Claims;

namespace Terra.Core.Common.Extensions;

/// <summary>
/// ClaimsPrincipal扩展方法
/// </summary>
public static class ClaimsPrincipalExtensions
{
    /// <summary>
    /// 获取用户ID
    /// </summary>
    /// <param name="principal">当前用户</param>
    /// <returns>用户ID，如果不存在则返回null</returns>
    public static Guid? GetUserId(this ClaimsPrincipal principal)
    {
        var nameIdentifier = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        return nameIdentifier != null ? Guid.Parse(nameIdentifier) : null;
    }

    /// <summary>
    /// 获取用户名
    /// </summary>
    /// <param name="principal">用户声明主体</param>
    /// <returns>用户名</returns>
    public static string GetUserName(this ClaimsPrincipal principal)
    {
        var claim = principal.FindFirst(ClaimTypes.Name);
        return claim?.Value;
    }
}